package cmd

import (
	"card/app/models"
	"card/dao"
	"card/pkg/cache"
	"card/pkg/console"
	"card/pkg/logger"
	"card/pkg/util"
	"context"
	"fmt"
	"github.com/spf13/cobra"
)

var CmdCache = &cobra.Command{
	Use:   "cache",
	Short: "Cache management",
}

var CmdCacheClear = &cobra.Command{
	Use:   "clear",
	Short: "Clear cache",
	Run:   runCacheClear,
}
var CmdCacheForget = &cobra.Command{
	Use:   "forget",
	Short: "Delete redis key, example: cache forget cache-key",
	Run:   runCacheForget,
}
var CmdCacheLoad = &cobra.Command{
	Use:   "load",
	Short: "数据库config预热",
	Run:   runCacheLoad,
}
var CmdCacheGet = &cobra.Command{
	Use:   "get",
	Short: "获取缓存",
	Run:   runCacheGet,
}
var cacheKey string

func init() {
	// 注册 cache 命令的子命令
	CmdCache.AddCommand(CmdCacheClear, CmdCacheLoad, CmdCacheForget, CmdCacheGet)
	// 设置 cache forget 命令的选项
	//go run main.go cache forget --key=links:all
	CmdCacheForget.Flags().StringVarP(&cacheKey, "key", "k", "", "KEY of the cache")
	CmdCacheForget.MarkFlagRequired("key")
	CmdCacheGet.Flags().StringVarP(&cacheKey, "key", "k", "", "KEY of the cache")
	CmdCacheGet.MarkFlagRequired("key")
}

func runCacheClear(cmd *cobra.Command, args []string) {
	cache.Flush()
	console.Success("Cache cleared.")
}
func runCacheForget(cmd *cobra.Command, args []string) {
	cache.Forget(cacheKey)
	console.Success(fmt.Sprintf("Cache key [%s] deleted.", cacheKey))
}
func runCacheGet(cmd *cobra.Command, args []string) {
	console.Info(cache.GetString(cacheKey))
}

// go run main.go cache load --env=local
func runCacheLoad(cmd *cobra.Command, args []string) {
	console.Success("cache load start")
	config := models.NewConfig(context.Background())
	list, err := config.All(dao.WithWhere("status = ?", 1))
	logger.LogIf(nil, err)
	for _, v := range list {
		if v.Type == 3 {
			cache.Set(v.Name, util.Parse(v.Value), 0)
		} else {
			cache.Set(v.Name, v.Value, 0)
		}
	}
	console.Success("cache load success")
}
